import { notification } from 'antd'

// 格式化参数
export function setParams(params: any) {
  const searchParams = new URLSearchParams()

  Object.keys(params).forEach((key: any) => {
    params[key] && searchParams.set(key, params[key])
  })

  return searchParams.toString()
}

/**
 * Base64 编码
 * @param str
 * @returns {string|void}
 */
export function toBtoa(str: string) {
  return str ? window.btoa(unescape(encodeURIComponent(JSON.stringify(str)))) : console.warn('str不能为空')
}

/**
 * Base64 解码
 * @param str
 * @returns {string|void}
 */
export function toAtob(str: string) {
  return str ? decodeURIComponent(escape(window.atob(str))) : console.warn('str不能为空')
}

// 浏览器环境
export const isBrowser = (): boolean => {
  return typeof window !== 'undefined'
}

export type NotificationType = 'success' | 'info' | 'warning' | 'error'
interface INotice {
  type?: NotificationType
  message?: string
  description?: string
}

// 通知封装
export const notice = ({ type = 'success', message = '友情提醒', description = '' }: INotice) => {
  notification[type]({ message, description })
}

// 还原滚动条位置
export const keepScrollbar = (key = 'scollbar-key') => {
  window.history.scrollRestoration = 'manual'
  // 保存滚动位置
  sessionStorage.setItem(key, JSON.stringify({ x: window.pageXOffset, y: window.pageYOffset }))
  // 页面返回后，滚动到之前的位置
  const position = JSON.parse(sessionStorage.getItem(key) || '[]')
  window.scrollTo(position.x, position.y)
}

// encode to html
export function encodeToHtml(str: string) {
  if (typeof str !== 'string') {
    return ''
  }

  if (!str.length) {
    return ''
  }

  return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"')
}

/**
 * 分享到
 * @param options
 * url: 项目访问地址
 * title: 项目名称
 * pics: 项目的封面图片地址
 * summary: 摘要
 * desc: 描述
 * appkey: 新浪微博分享appkey
 */
export const shareTo = (options: any) => {
  const { url, title, pics, type, summary, desc, appkey } = options

  // qq空间接口的传参
  if (type === 'qzone') {
    window.open(`https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${url}?sharesource=qzone&title=${title}&pics=${pics}&summary=${summary}`)
  }
  // 新浪微博接口的传参
  if (type === 'weibo') {
    window.open(`http://service.weibo.com/share/share.php?url=${url}?sharesource=weibo&title=${title}&pic=${pics}&appkey=${appkey}`)
  }
  // qq好友接口的传参
  if (type === 'qq') {
    window.open(`http://connect.qq.com/widget/shareqq/index.html?url=${url}?sharesource=qzone&title=${title}&pics=${pics}&summary=${summary}&desc=${desc}`)
  }
}
